<?php
/**
 * Created by JetBrains PhpStorm.
 * User: TongBc
 * Date: 14-7-7
 */
if(!$_SESSION['memberID']) {
    exit('未登录或登录超时！');
}
include('../common/autoload.php');
include '../class/SmsTpl.class.php';
$action = trim($_REQUEST['action']);
$token = $_REQUEST['token'];
$soap = SoapInit::GetSoapInside();
$smstpl=new SmsTpl($GLOBALS['le']);
// print_r($_REQUEST);
// exit;
switch($action) {
	case 'saveSms':
		$pid = $_REQUEST['pid']+0;
		$lid = $_REQUEST['lid']+0;
		$sid = $_REQUEST['sid']+0;
		$sms = $smstpl->GetRevFormat(trim($_REQUEST['sms']));
		// 存在 pid 说明针对某一门票
		if($pid){
			if($sid){ // 如果存在就更新
				$sql="UPDATE uu_sms_format SET cformat='$sms' WHERE id=$sid AND pid=$pid";
			}else{
				$sql="INSERT INTO uu_sms_format (pid,cformat) VALUES ($pid,'$sms')";
			}
			$GLOBALS['le']->query($sql) ? echoExit('模板保存成功'):echoExit('模板保存失败');
		}

		// 针对景区，则所有的门票都要有模板（问题：可能有的存在）
		// 1.先找出所有的门票 2.找出存在的门票 pid 3.移除存在的 pid
		$pidArr = array();
		$pidArr2 = array();
		$diffArr= array();
		$aid = '';
		$sql="SELECT id,apply_did,pid FROM uu_jq_ticket WHERE landid=$lid";
		$GLOBALS['le']->query($sql);
		while($row = $GLOBALS['le']->fetch_assoc()){
			$pidArr[]=$row['pid'];
			$aid =  $row['apply_did'];
		}
		if(!count($pidArr)) echoExit('该景区未添加任何门票，请先添加门票');
		$sql="SELECT pid FROM uu_sms_format WHERE pid IN (".implode(',',$pidArr).")";
		$GLOBALS['le']->query($sql);
		while($row = $GLOBALS['le']->fetch_assoc()){
			$pidArr2[]=$row['pid'];
		}
		if(count($diffArr))
		{
			$diffArr = array_diff($pidArr, $pidArr2);
			$sql="INSERT INTO uu_sms_format (did,pid,cformat) VALUES ";
			foreach($diffArr as $v){
				$sql.='('.$aid.','.$v.',"'.$sms.'"),';
			}
			$sql=substr($sql,0,-1);
			$GLOBALS['le']->query($sql) ? echoExit('模板保存成功'):echoExit('模板保存失败');
		}
		
		break;
	// 根据 Pid 获取短信模板
	case 'getSms':
		$pid = $_REQUEST['pid']+0;
		echo json_encode(array(
			's'=>'success',
			'content'=>$smstpl->GetFormatSmsTpl($pid),
			'pid'=>$pid,
			'id'=>$smstpl->smsid
		));
		break;
    default:break;
}

function echoExit($msg){
	echo $msg;exit;
}

?>